# 设置工作目录并读取数据
setwd("F:/第6章/01-任务程序")
setwd("E:/R语言商务数据分析实战/第6章/任务程序")
df.final <- read.csv("./tmp/df_final.csv", stringsAsFactors = FALSE, fileEncoding = "GBK")

# 建模
# 对预处理后的数据分训练集和测试集
line.cols <- names(df.final)
line.cols <- setdiff(line.cols, "Idx")
train.data <- df.final[ ! is.na(df.final$target), line.cols]
test.data <- df.final[is.na(df.final$target), line.cols]
test.idx <- df.final[is.na(df.final$target), "Idx"]
test.idx <- data.frame(Idx = test.idx)
test.data[, "target"] <- NULL
library(gbm)
library(pROC)
gbm.model <- gbm(target ~ ., data = train.data, distribution = "adaboost", 
                 n.trees = 1500, shrinkage = 0.01, 
                 interaction.depth = 4, bag.fraction = 0.5, 
                 train.fraction = 0.5, n.minobsinnode = 10, 
                 cv.folds = 3, keep.data = TRUE, verbose = FALSE, n.cores = 2)
best.iter <- gbm.perf(gbm.model, method = "cv")  # 用交叉检验确定最佳迭代次数
best.iter
impval <- summary(gbm.model, best.iter)  # 查看特征重要程度

# 画出特征重要性图
barplot(impval[c(1 : 20), 2], names = impval[c(1 : 20), 1], 
        col = rainbow(20), las = 2, cex.names = 0.5, ylim = c(0, 4),
        ylab = "特征的重要程度")
legend(16, 4.1, legend = impval[c(1 : 20), 1], 
       fill = rainbow(20), bty = "o", ce)


# 评价模型
gbm.pred <- predict.gbm(gbm.model, test.data, type = "response" )  # 预测
final.test <- read.csv("./data/Test_Master_result.csv")  # 导入真实结果
dbReadTable(con, "6_task_training_master")
test.merge <- merge(test.idx, final.test, by = "Idx")
library(ROCR)
pred.both <- prediction(gbm.pred, test.merge$target)
perf.both <- performance(pred.both, "tpr", "fpr")
plot(perf.both, main = "ROC曲线", col = "blue", lwd = 5)  # 画出ROC曲线图
roc(test.merge$target, gbm.pred)  # 求出曲线下方面积
